package de.reondo.jos;

import org.jgrapht.Graph;
import org.jgrapht.graph.AbstractBaseGraph;

import de.reondo.jos.filters.IFilter;

public class GraphUtils {

	public static <V> V getVertexWithMaximumEdges(Graph<V, ?> graph) {
		V maxV = null;
		int maxCount = 0;
		for (V vertex : graph.vertexSet()) {
			if (maxV == null) {
				maxV = vertex;
			}
			int c = graph.edgesOf(vertex).size();
			if (c > maxCount) {
				maxCount = c;
				maxV = vertex;
			}
		}
		return maxV;
	}
	
	public static <V, E> Graph<V, E> filterVertices(AbstractBaseGraph<V, E> graph, IFilter<V> vertexFilter, IFilter<E> edgeFilter) {
		@SuppressWarnings("unchecked")
        Graph<V, E> result = (Graph<V, E>) graph.clone();
		// first remove vertices, which removed attached edges, too
		if (vertexFilter != null) {
			for (V v : graph.vertexSet()) {
				if (!vertexFilter.accept(v)) {
					result.removeVertex(v);
				}
			}
		}
		if (edgeFilter != null) {
			for (E e : graph.edgeSet()) {
				if (!edgeFilter.accept(e)) {
					result.removeEdge(e);
				}
			}
		}
		return result;
	}
	
}
